package com.aidex.biz.controller;

import com.aidex.biz.domain.SearchInfo;
import com.aidex.biz.service.SearchInfoService;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.DateUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.poi.ExcelUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.util.List;

/**
 * 产品信息Controller
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-03-31
 */
@RestController
@RequestMapping("/biz/bizSearchInfo")
public class SearchInfoController extends BaseController {
    @Autowired
    private SearchInfoService searchInfoService;

    /**
     * 查询产品信息列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:list')")
    @GetMapping("/list")
    public R<PageInfo> list(SearchInfo searchInfo, HttpServletRequest request, HttpServletResponse response) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            searchInfo.setCompanyId(null);
        } else {
            searchInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        searchInfo.setPage(new PageDomain(request, response));
        return R.data(searchInfoService.findPage(searchInfo));
    }

    /**
     * 获取产品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:query')")
    @GetMapping(value = "/{id}")
    public R<SearchInfo> detail(@PathVariable("id") String id) {
        return R.data(searchInfoService.get(id));
    }

    /**
     * 新增产品信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:add')")
    @Log(title = "产品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated SearchInfo searchInfo) {
        return R.status(searchInfoService.save(searchInfo));
    }

    /**
     * 修改产品信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:edit')")
    @Log(title = "产品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated SearchInfo searchInfo) {
        return R.status(searchInfoService.save(searchInfo));
    }


    /**
     * 删除产品信息
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:remove')")
    @Log(title = "产品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.status(searchInfoService.deleteSearchInfoByIds(ids));
    }

    /**
     * 获取最大编号
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:query')")
    @GetMapping("/findMaxSort")
    public R findMaxSort() {
        return R.data(searchInfoService.findMaxSort(new SearchInfo()));
    }

    /**
     * 导出产品信息列表
     */
    @PreAuthorize("@ss.hasPermi('biz:bizSearchInfo:export')")
    @Log(title = "产品信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(SearchInfo searchInfo, HttpServletResponse response) {

        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            searchInfo.setCompanyId(null);
        } else {
            searchInfo.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<SearchInfo> list = searchInfoService.findList(searchInfo);
        //拼接字符串
        StringBuffer text = new StringBuffer();
        for (SearchInfo searchInfo1 : list) {
            if (!StringUtils.isNull(searchInfo1.getDetailsId())) {
                text.append(searchInfo1.getDetailsId());
                text.append("\r\n");//换行字符
            }
        }
        exportTxt(response, text.toString());

    }

    @Log(title = "产品信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<SearchInfo> util = new ExcelUtil<SearchInfo>(SearchInfo.class);
        List<SearchInfo> searchInfoList = util.importExcel(file.getInputStream());
        String message = searchInfoService.importData(searchInfoList);
        return AjaxResult.success(message);
    }

    public void exportTxt(HttpServletResponse response, String text) {
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition",
                "attachment;filename=" + genAttachmentFileName("药品链接" + DateUtils.getTime(), "JSON_FOR_UCC_")
                //设置名称格式，没有这个中文名称无法显示
                + ".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(text.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            //LOGGER.error("导出文件文件出错:{}",e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
                //LOGGER.error("关闭流对象出错 e:{}",e);
            }
        }
    }

    public String genAttachmentFileName(String cnName, String defaultName) {
        try {
            cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
        } catch (Exception e) {
            cnName = defaultName;
        }
        return cnName;
    }

}
